package create

import (
	"fmt"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"

	"gitcode.com/goinit/goinit/internal/pkg/filex"
	"gitcode.com/goinit/goinit/internal/pkg/mod"
	"gitcode.com/goinit/goinit/internal/tpl/handle"
	"gitcode.com/goinit/goinit/internal/tpl/model"
	"gitcode.com/goinit/goinit/internal/tpl/repository"
	"gitcode.com/goinit/goinit/internal/tpl/service"
)

var Root = &cobra.Command{
	Use:     "create",
	Short:   "Create a new handler/service/repository/model/all",
	Example: "goinit create handler user",
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Help()
	},
}

var moduleName string

func init() {
	Root.PersistentFlags().StringVarP(&moduleName, "module", "m", "", "module name")
	Root.AddCommand(cmdByAll)
	Root.AddCommand(cmdByModel)
	Root.AddCommand(cmdByHandler)
	Root.AddCommand(cmdByService)
	Root.AddCommand(cmdByRepository)
}

func values(fileName string) (map[string]string, string, error) {
	modName, err := mod.Name()
	if modName == "" || err != nil {
		fmt.Println("go.mod 文件不存在")
		return nil, modName, err
	}

	return map[string]string{
		"ModName":        modName,
		"HandlerName":    fileName,
		"ServiceName":    fileName,
		"RepositoryName": fileName,
		"ModelName":      fileName,
	}, modName, nil
}

func touchFile(method string, cmd *cobra.Command, args []string) {
	if len(args) < 1 {
		cmd.Help()
		return
	}

	fileName := args[0]
	if fileName == "" || (moduleName == "" && strings.ToLower(method) != "model") {
		cmd.Help()
		return
	}

	value, _, err := values(fileName)
	if err != nil {
		return
	}

	path := filepath.Join("internal", "app", moduleName, method, fileName+".go")
	if strings.ToLower(method) == "model" {
		path = filepath.Join("internal", "model", fileName+".go")
	}

	var content []byte
	switch strings.ToLower(method) {
	case "handler":
		content = handle.Handle
	case "service":
		content = service.Service
	case "repository":
		content = repository.Repository

	case "model":
		content = model.Model
	}

	filex.Create(path, string(content), value)
}
